/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import handler.database;
import java.sql.*;
import javax.servlet.http.HttpSession;
import model.User;
import model.Users;

/**
 *
 * @author ifan
 */
public class LoginServlet extends HttpServlet {

    Users loginUsers;

    @Override
    public void init() throws ServletException {
        super.init();

        loginUsers = new Users();
        getServletContext().setAttribute("loginUsers", loginUsers);
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet LoginServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet LoginServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection conn = null;

        String username = "";
        String userpass = "";


        String strQuery = "";
        Statement statement = null;
        ResultSet result = null;
        HttpSession session = request.getSession(true);
        try {
            database db = new database();
            conn = db.getConnection();
            if (request.getParameter("username") != null && request.getParameter("username").length() > 0 && request.getParameter("password") != null && request.getParameter("password").length() > 0) {
                username = request.getParameter("username").toString();
                userpass = request.getParameter("password").toString();
                strQuery = "SELECT * from user where username='" + username + "' and  password='" + userpass + "'";
                System.out.println(strQuery);
                statement = conn.createStatement();
                result = statement.executeQuery(strQuery);
                int id = 0;
                int count = 0;
                boolean admin = false;
                boolean ban = false;
                while (result.next()) {
                    System.out.println("tes");
                    id = Integer.parseInt(result.getString(1));
                    session.setAttribute("username", result.getString(2));
                    session.setAttribute("id",id);
                    session.setAttribute("role", result.getString(5));
                    System.out.println(result.getString(5));
                    if(result.getString(5).equalsIgnoreCase("admin")) {
                        admin=true;
                    }
                    if(Integer.parseInt(result.getString(7))==1) {
                        ban = true;
                    }
                    count++;
                }
                if (count > 0 && !ban) {
                    if(admin) {
                        response.sendRedirect("admin.jsp");
                    } else {
                        User user = new User(id, username);
                        loginUsers.add(user);
                        response.sendRedirect("chat.jsp");
                    }
                } else {
                    if(ban) {
                        System.out.println("gagal login");
                    }
                    response.sendRedirect("index.jsp");
                }
            } else {
                response.sendRedirect("index.jsp");
            }
            conn.close();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
